import { arrIsSame } from "./array";

function objToFormData(obj) {
    const formData = new FormData()
    for (const key in obj) {
        if (obj.hasOwnProperty(key)) {
            formData.append(key, obj[key])
        }
    }
    return formData
}

// 深拷贝
function deepClone(obj) {
    var result = Array.isArray(obj) ? [] : {};
    for (var key in obj) {
        if (obj.hasOwnProperty(key)) {
            if (typeof obj[key] === 'object' && obj[key] !== null) {
                result[key] = deepCopy(obj[key]);
            } else {
                result[key] = obj[key];
            }
        }
    }
    return result;
}

// 判断两个对象是否相等
// 不判断undefined、任意的函数以及 symbol 值
export const isObjectValueEqual = (a, b) => {
    if (typeof a === 'object' && typeof b === 'object') {
        const aKeyArr = Object.keys(a)
        const aValArr = Object.values(a)
        const bKeyArr = Object.keys(b)
        const bValArr = Object.values(b)
        if (arrIsSame(aKeyArr, bKeyArr) && arrIsSame(aValArr, bValArr)) {
            return true
        }
    }
    return false
}

// 将对象拼接成字符串
export const objToStr = (obj, isUrlQuery = true) => {
    if (typeof obj === 'object') {
        const keyArr = Object.keys(obj)
        if (keyArr.length > 0) {
            const arr = []
            keyArr.forEach(item => {
                arr.push(`${item}=${obj[item]}`)
            })
            if (isUrlQuery){
                return `?${arr.join('&')}`
            }
            return arr.join('&')
        }
    }
    return ''
}

export { objToFormData, deepClone }